<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      v-model="form"
      :data="data"
      :page.sync="page"
      :search.sync="query"
      :permission="permissionList"
      :before-open="beforeOpen"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @selection-change="selectionChange"
      @search-change="searchChange"
      @search-reset="searchReset"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="typeSearch">
        <el-select v-model="query.type" placeholder="请选择 规则类型" multiple>
          <el-option v-for="item in options" :key="item.value" :label="item.value" :value="item.value"></el-option>
        </el-select>
      </template>
      <template slot="codeForm">
        <el-input placeholder="请输入编码" v-model="form.code" disabled></el-input>
      </template>
      <template slot="schemeSearch">
        <el-input placeholder="请输入 方案名称 " v-model="query.scheme"></el-input>
      </template>
      <template slot-scope="{}" slot="rulesContentLabel"><span style="color: red">*</span>规则内容</template>
      <template slot-scope="{}" slot="rulesContentForm" v-if="form.name">
        <avue-form ref="warehousePropertiesForm" v-model="form" :option="rulesOption">
          <!--超收规则-->
          <template slot-scope="{}" slot="overlimitRate">
            <div>
              <el-radio v-remove-aria-hidden v-model="form.constraintOperator" :disabled="ruleContent === 'view'" label="=" @input="form.constraintValue = true"
                >不限制</el-radio
              >
              <el-radio v-remove-aria-hidden v-model="form.constraintOperator" :disabled="ruleContent === 'view'" label=">" @input="form.constraintValue = ''"
                >允许超出
                <el-input
                  style="width: 40%"
                  :disabled="ruleContent === 'view' || form.constraintOperator === '='"
                  class="overpaymentRatio-value"
                  v-model="form.constraintValue"
                  type="number"
                  min="1"
                  placeholder=""
                ></el-input>
                %
              </el-radio>
            </div>
          </template>
          <!--先进先出规则-->
          <template slot-scope="{}" slot="fifoRequiredLabel">
            <el-tooltip class="item" effect="dark" content="根据物料生产日期控制出库顺序" placement="top-start">
              <i class="el-icon-info"></i>
            </el-tooltip>
            <span>&nbsp;管控先进先出:</span>
          </template>
          <template slot-scope="{}" slot="overCollarMentRatio">
            <div>
              <el-radio-group v-model="form.constraintOperator">
                <el-radio v-remove-aria-hidden label="=" :disabled="ruleContent === 'view'" @input="form.constraintValue = true">不限制 </el-radio>
                <el-radio v-remove-aria-hidden label=">" :disabled="ruleContent === 'view'" @input="form.constraintValue = ''">
                  允许超领（订单数量）比例:
                  <el-input
                    style="width: 40%"
                    :disabled="form.constraintOperator === '=' || ruleContent === 'view'"
                    class="overpaymentRatio-value"
                    v-model="form.constraintValue"
                    type="number"
                    min="1"
                    placeholder=""
                  ></el-input>
                  %
                </el-radio>
              </el-radio-group>
            </div>
          </template>
        </avue-form>
      </template>
      <template slot="menuLeft">
        <el-button type="danger" :disabled="!selectionList.length" size="small" icon="el-icon-delete" @click="handleDetailDelete" v-if="permission.businessRules_del"
          >删 除
        </el-button>
      </template>
      <!--      <template slot="menuRight">-->
      <!--        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>-->
      <!--      </template>-->
    </avue-crud>
  </basic-container>
</template>
<script>
import { mapGetters } from 'vuex';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
import { getList, add, del, update, checkIsUse, detail, checkRepeatScheme, checkRepeatIsDefault } from '@/api/warehouse/businessRules';
import { filterEmptyValues } from '@/util/util';

export default {
  name: 'businessRules', // 会渲染成传入的componentName
  components: {
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      msdLevels: [],
      ruleType: '',
      ruleContent: '', //
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      options: [
        {
          code: 'RECEIVE_RULE',
          value: '收料规则'
        },
        {
          code: 'OUTBOUND_RULE',
          value: '出库规则'
        },
        {
          code: 'WAREHOUSE_MANAGE_RULE',
          value: '库内管理规则'
        }
      ],
      selectionList: [],
      lineInventoryList: [],
      data: [],
      option: {
        calcHeight: 30,
        height: 'calc(100vh - 360px)',
        tip: false,
        searchShow: true,
        labelWidth: 150,
        searchMenuSpan: 4,
        searchMenuPosition: 'right',
        selection: true,
        border: true,
        index: true,
        viewBtn: true,
        editBtn: true,
        delBtn: true,
        addTitle: '新增业务规则',
        editTitle: '编辑业务规则',
        viewTitle: '查看业务规则',
        addBtn: true,
        indexLabel: '序号',
        columnBtn: false,
        column: [
          {
            label: '方案名称',
            prop: 'scheme',
            search: true,
            searchOrder: 2,
            rules: [
              {
                required: true,
                message: '请选择输入方案名称',
                trigger: 'blur'
              }
            ],
            blur: ({ column, value }) => {
              this.checkRepeatScheme(value);
            }
          },
          {
            label: '方案编码',
            prop: 'code',
            placeholder: '系统自动生成'
          },
          {
            label: '规则类型',
            prop: 'type',
            type: 'select',
            // type: 'cascader',
            cascader: ['name'],
            search: true,
            filterable: true,
            searchOrder: 1,
            order: 1,
            searchSpan: 6,
            dicUrl: '/api/mes-warehouse/rule-scheme/get-rule-type',
            props: {
              label: 'value',
              value: 'code'
            },
            dicFormatter: (res) => {
              return res.data;
            },
            rules: [
              {
                required: true,
                message: '请选择规则类型',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '规则名称',
            prop: 'name',
            type: 'select',
            search: true,
            searchType: 'input',
            searchSpan: 6,
            order: 2,
            searchOrder: 3,
            dicUrl: '/api/mes-warehouse/rule-scheme/get-rule-category?code={{key}}',
            props: {
              label: 'value',
              value: 'value'
            },
            dicFormatter: (res) => {
              return res.data;
            },
            rules: [
              {
                required: true,
                message: '请选择规则名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '规则内容',
            prop: 'rulesContent',
            span: 24,
            hide: true,
            formslot: true
          },
          {
            label: '状态',
            prop: 'status',
            type: 'switch',
            value: 1,
            dicData: [
              { label: '禁用', value: 0 },
              { label: '启用', value: 1 }
            ],
            rules: [
              {
                required: true,
                message: '请选择状态',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '是否默认规则',
            prop: 'isDefault',
            type: 'switch',
            dicData: [
              {
                label: '否',
                value: false
              },
              {
                label: '是',
                value: true
              }
            ],
            value: false
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            span: 24
          },
          {
            label: '更新人',
            prop: 'updateUserName',
            addDisplay: false,
            viewDisplay: false,
            editDisplay: false
          },
          {
            label: '最新更新时间',
            prop: 'updateTime',
            addDisplay: false,
            viewDisplay: false,
            editDisplay: false
          }
        ]
      },
      rulesOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: '150',
        column: [
          {
            label: '允许超收',
            prop: 'isAllowOverlimit',
            // labelslot: true,
            type: 'switch',
            labelTip: '允许超收时将控制该物料收货数量上限',
            value: false,
            order: 6,
            align: 'center',
            span: 24,
            dicData: [
              {
                label: '否',
                value: false
              },
              {
                label: '是',
                value: true
              }
            ],
            control: (val, form) => {
              if (this.form.name === '超收规则') {
                return {
                  isAllowOverlimit: { display: true }
                };
              } else {
                return {
                  isAllowOverlimit: { display: false }
                };
              }
            }
          },
          {
            label: '超收比例',
            prop: 'overlimitRate',
            span: 24,
            labelWidth: 150,
            type: 'radio',
            formslot: true,
            display: false,
            order: 8,
            formatter: (val, value, label) => {
              if (value) {
                return value + '%';
              } else {
                return '';
              }
            },
            control: (val, form) => {
              if (this.form.name === '超收规则' && form.isAllowOverlimit) {
                return {
                  overlimitRate: { display: true }
                };
              } else {
                return {
                  overlimitRate: { display: false }
                };
              }
            }
          },
          {
            label: '管控先进先出',
            prop: 'fifoRequired',
            type: 'switch',
            align: 'center',
            row: true,
            value: false,
            dicData: [
              {
                label: '否',
                value: false
              },
              {
                label: '是',
                value: true
              }
            ],
            order: 7,
            control: (val, form) => {
              if (this.form.name === '先进先出') {
                return {
                  fifoRequired: { display: true }
                };
              } else {
                return {
                  fifoRequired: { display: false }
                };
              }
            }
          },
          {
            label: '允许超领',
            prop: 'isAllowOverreceive',
            span: 24,
            type: 'switch',
            labelTip: '允许超领时将控制该物料收货数量上限',
            value: false,
            hide: true,
            dicData: [
              {
                label: '否',
                value: false
              },
              {
                label: '是',
                value: true
              }
            ],
            control: (val, form) => {
              if (this.form.name === '超领规则') {
                return {
                  isAllowOverreceive: { display: true }
                };
              } else {
                return {
                  isAllowOverreceive: { display: false }
                };
              }
            }
          },
          {
            label: '超领比例',
            prop: 'overCollarMentRatio',
            span: 24,
            labelWidth: 150,
            type: 'radio',
            formslot: true,
            display: false,
            control: (val, form) => {
              if (this.form.name === '超领规则' && this.form.isAllowOverreceive === true) {
                return {
                  overCollarMentRatio: { display: true }
                };
              } else {
                return {
                  overCollarMentRatio: { display: false }
                };
              }
            }
          },
          {
            label: '保质期天数',
            prop: 'expirationDays',
            min: 0,
            span: 10,
            precision: 0,
            type: 'number',
            control: (val, form) => {
              if (this.form.name === '保质期天数') {
                return {
                  expirationDays: { display: true }
                };
              } else {
                return {
                  expirationDays: { display: false }
                };
              }
            }
          },
          {
            label: '保质期预警提前天数',
            prop: 'expirationWarningDays',
            min: 0,
            span: 10,
            precision: 0,
            type: 'number',
            control: (val, form) => {
              if (this.form.name === '保质期预警天数') {
                return {
                  expirationWarningDays: { display: true }
                };
              } else {
                return {
                  expirationWarningDays: { display: false }
                };
              }
            }
          }
        ]
      }
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  directives: {
    removeAriaHidden: {
      bind(event, bingding) {
        let ariaHidden = event.querySelectorAll('.el-radio__original');
        ariaHidden.forEach((item) => {
          item.removeAttribute('aria-hidden');
        });
      }
    }
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        viewBtn: this.vaildData(this.permission.businessRules_view, false),
        editBtn: this.vaildData(this.permission.businessRules_eidt, false),
        addBtn: this.vaildData(this.permission.businessRules_add, false)
      };
    },
    ids() {
      const idList = this.selectionList.map((item) => item.id);
      return idList;
    }
  },
  methods: {
    rowSave(row, done, loading) {
      this.$refs.warehousePropertiesForm.validate(async (valid, gone) => {
        if (valid) {
          const res = await this.handleCheckIsDefault();
          const isCanSave = res.data.isSuccess;
          const msg = res.data.msg;
          if (isCanSave) {
            const res = await this.saveOrUpdateData(add, done, loading, gone);
          } else {
            this.$confirm(`${msg}`, {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              dangerouslyUseHTMLString: true,
              type: 'warning'
            })
              .then(async () => {
                try {
                  await this.saveOrUpdateData(add, done, loading, gone);
                  // this.onLoad(this.page);
                  //  done();
                } catch (e) {
                  console.warn(e);
                }
              })
              .catch(() => {
                gone();
                loading();
              });
          }
        } else {
          loading();
        }
      });
    },
    async saveOrUpdateData(func, done, loading, gone) {
      try {
        if (this.form.name === '超领规则' && !this.form.constraintValue && this.form.constraintOperator === '>') {
          this.$message.error('允许超领,超领比例不能为0');
          loading();
          gone();
          return;
        }
        if (this.form.isAllowOverreceive && !this.form.constraintValue) {
          this.$message.error('请设置超领比例');
          loading();
          gone();
          return;
        }
        if (this.form.name === '超收规则' && !this.form.constraintValue && this.form.constraintOperator === '>') {
          this.$message.error('允许超收,超收比例不能为0');
          loading();
          gone();
          return;
        }
        if (this.form.isAllowOverlimit && !this.form.constraintValue) {
          this.$message.error('请设置超收比例');
          loading();
          gone();
          return;
        }
        if (this.form.name === '先进先出' && this.form.fifoRequired === undefined && this.form.fifoRequired === null) {
          this.$message.error('管控先进先出不能为空');
          loading();
          gone();
          return;
        }
        const data = this.formatData();
        const res = await func(data);
        done();
        this.onLoad(this.page);
        this.$message.success('操作成功');
      } catch (e) {
        console.warn(e);
        loading();
      }
    },
    rowUpdate(row, index, done, loading) {
      this.$refs.warehousePropertiesForm.validate(async (valid, gone) => {
        if (valid) {
          const res = await this.handleCheckIsDefault();
          const isCanSave = res.data.isSuccess;
          const msg = res.data.msg;
          if (isCanSave) {
            const res = await this.saveOrUpdateData(add, done, loading, gone);
            // this.onLoad(this.page);
            // done();
          } else {
            this.$confirm(`${msg}`, {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              dangerouslyUseHTMLString: true,
              type: 'warning'
            })
              .then(async () => {
                try {
                  await this.saveOrUpdateData(add, done, loading, gone);
                  // this.$message.success('修改成功');
                  // this.onLoad(this.page);
                  // done();
                } catch (e) {
                  console.warn(e);
                }
              })
              .catch(() => {
                gone();
                loading();
              });
          }
        } else {
          loading();
        }
      });
    },
    async checkIsDefault(id) {
      try {
        const data = id ? [id] : this.selectionList.map((item) => item.id);
        const isUse = await checkIsUse(data);
        return isUse.data;
      } catch (e) {
        console.warn(e);
      }
    },
    async rowDel(row) {
      const res = await this.checkIsDefault(row.id);
      const isCanDel = res.data.isSuccess;
      const msg = res.data.msg;
      if (isCanDel) {
        try {
          this.$confirm('确定将选择数据删除?', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(async () => {
              await del([row.id]);
            })
            .then(() => {
              this.onLoad(this.page);
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
            });
        } catch (e) {
          console.warn(e);
        }
      } else {
        this.$confirm(`${msg}`, {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          dangerouslyUseHTMLString: true,
          type: 'warning'
        }).then(async () => {
          try {
            await del([row.id]);
            this.$message.success('删除成功');
            this.onLoad(this.page);
          } catch (e) {
            console.warn(e);
          }
        });
      }
    },
    async checkRepeatScheme(val) {
      try {
        const data = {
          scheme: val
        };
        if (this.form.id) {
          data.id = this.form.id;
        }
        const res = await checkRepeatScheme(data);
      } catch (e) {
        this.form.scheme = '';
        console.log(e);
      }
    },
    async handleDetailDelete() {
      const res = await this.checkIsDefault();
      const isCanDel = res.data.isSuccess;
      const msg = res.data.msg;
      if (isCanDel) {
        try {
          this.$confirm('确定将选择数据删除?', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            dangerouslyUseHTMLString: true,
            type: 'warning'
          })
            .then(async () => {
              await del(this.selectionList.map((item) => item.id));
            })
            .then(() => {
              this.onLoad(this.page);
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
            });
        } catch (e) {
          console.warn(e);
        }
      } else {
        this.$confirm(`${msg}`, {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          try {
            await del(this.ids);
            this.$message.success('删除成功');
            this.onLoad(this.page);
          } catch (e) {
            console.warn(e);
          }
        });
      }
    },

    async beforeOpen(done, type) {
      if (['view', 'edit'].includes(type)) {
        const res = await detail(this.form.id);
        const form = res.data.data || {};
        if (form.name === '保质期天数') {
          form.expirationDays = form.constraintValue;
          delete form.constraintValue;
        } else if (form.name === '保质期预警天数') {
          form.expirationWarningDays = form.constraintValue;
          delete form.constraintValue;
        } else if (form.name === '先进先出') {
          form.fifoRequired = this.transferConstraintValue(form.constraintValue);
          delete form.constraintValue;
          //this.$set(this.form, 'fifoRequired', form.constraintValue);
        } else if (form.name === '超收规则') {
          form.isAllowOverlimit = this.transferConstraintValue(form.constraintValue);
        } else if (form.name === '超领规则') {
          form.isAllowOverreceive = this.transferConstraintValue(form.constraintValue);
        }
        this.form = form;
      }
      done();
    },
    transferConstraintValue(value) {
      if (value === 'true') {
        return true;
      } else if (value === 'false') {
        return false;
      } else {
        return Number(value);
      }
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    //格式化参数
    formatData() {
      const form = this._cloneDeep(this.form);
      const fieldMap = {
        保质期天数: 'STORAGE_TIME',
        保质期预警天数: 'STORAGE_WARNING_TIME',
        超收规则: 'OVER_LIMIT',
        先进先出: 'FIFO',
        超领管控: 'OVER_RECEIVE'
      };
      const typeMap = {
        WAREHOUSE_MANAGE_RULE: '库内管理规则',
        OUTBOUND_RULE: '出库规则',
        RECEIVE_RULE: '收料规则',
        库内管理规则: '库内管理规则',
        出库规则: '出库规则',
        收料规则: '收料规则'
      };

      const baseParams = {
        isDefault: form.isDefault,
        name: form.name,
        code: form.code,
        scheme: form.scheme,
        status: form.status,
        type: typeMap[form.type],
        remark: form.remark,
        id: form.id,
        constraintField: fieldMap[form.name],
        constraintOperator: form.constraintOperator || '='
      };
      if (form.id) {
        baseParams.id = form.id;
      }
      //超收规则 规则  overlimitRate  isAllowOverlimit
      if (form.name === '超收规则') {
        if (!form.isAllowOverlimit) {
          baseParams.constraintValue = false;
        } else {
          baseParams.constraintValue = form.constraintValue || true;
        }
      } else if (form.name === '超领规则') {
        console.log(form.isAllowOverreceive, form.constraintValue);
        if (!form.isAllowOverreceive) {
          baseParams.constraintValue = false;
        } else {
          baseParams.constraintValue = form.constraintValue || true;
        }
      }
      //先进先出 fifoRequired
      else if (form.name === '先进先出') {
        baseParams.constraintValue = form.fifoRequired;
      } else if (form.name === '保质期天数') {
        baseParams.constraintValue = form.expirationDays;
      } else if (form.name === '保质期预警天数') {
        baseParams.constraintValue = form.expirationWarningDays;
      }
      console.log('baseParams', baseParams);
      return baseParams;
    },
    async onLoad(page, params = {}) {
      this.loading = true;
      let rspParams = filterEmptyValues(this._cloneDeep(this.query));
      try {
        if (Array.isArray(rspParams.type) && rspParams.type.length > 0) {
          rspParams.type = rspParams.type.join(',');
        } else {
          delete rspParams.type;
        }
        const res = await getList(page.currentPage, page.pageSize, rspParams);
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
      } catch (e) {
        console.warn(e);
      } finally {
        this.loading = false;
      }
    },
    async handleCheckIsDefault() {
      try {
        const data = {
          name: this.form.name,
          defaultFlag: this.form.isDefault
        };
        if (this.form.id) {
          data.id = this.form.id;
        }
        const res = await checkRepeatIsDefault(data);
        return res.data;
      } catch (e) {
        console.log(e);
      }
    }
    // updateCode() {
    //   const dateStr = this.$moment(new Date()).format('YYYYMMDD');
    //   this.form.code = 'R' + dateStr + guid().substr(24, 12);
    // }
  }
};
</script>
<style lang="scss" scoped></style>
